﻿using Api.Model;
using Api.Dal.Tools;
using Microsoft.Data.SqlClient;
using System.Data;
using System.Reflection.Metadata;
using Api.Model.Migrations;
using System.Text.RegularExpressions;
using System.Reflection.Metadata.Ecma335;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;
using System.Text;

namespace Api.Dal
{
    public class UserDal
    {
        public static int GetCount()
        {
            int count = 0;
            EfDemoContext ef = new EfDemoContext();
            if (ef.Users.IsNullOrEmpty())
            {
                return 0;
            }
            count = ef.Users.Select(u=>u.id).Max();
            return count;
        }
        //static Blob imageNull { get; set; }
        public static User? GetUserById(int UserNo)
        {
            EfDemoContext ef = new EfDemoContext();
            User u = ef.Users.Where(u => (string.Equals(u.id, UserNo))).First();
            return u;
        }

        public static User? GetUserByName(string name)
        {
            EfDemoContext ef = new EfDemoContext();
            User u = ef.Users.Where(u => (string.Equals(u.name, name))).First();
            return u;
        }

        //public static User? GetUserByNameAndPwd(string UserName, string password)
        //{
        //    EfDemoContext ef = new EfDemoContext();
        //    User u = ef.Users.Where(u => (string.Equals(u.name, UserName) && string.Equals(u.password, password))).First();
        //    return u;
        //}

        public static User? GetUser(User user)
        {
            User? storedu = GetUserByName(user.name);
            if (storedu == null) return storedu;

            if (Md5Tool.ValidatePassword(user.password, storedu.password) == false)
            {
                throw new Exception("用户名或密码错误");
            };

            EfDemoContext ef = new EfDemoContext();
            User? u = ef.Users.Where(u => 
                (user.name == "N/A" || string.Equals(u.name, user.name) && 
                (true )) &&
                (user.id == -1 || user.id == u.id) &&
                (user.phone == "N/A" || string.Equals( user.phone, u.phone) ) &&
                (user.email == "N/A" || string.Equals(user.email, u.email) ) &&
                (user.address == "N/A" || string.Equals(user.address, u.address) ) 
                // &&(user.Token == "N/A" || string.Equals(user.Token, u.Token))
            ).FirstOrDefault(); 
            return u;
        }

        public static string AddUser(User u) 
        {
            EfDemoContext ef = new EfDemoContext();
            string valid = IsValid(u);
            if(!string.Equals(valid, ""))
            {
                return valid;
            }
            //MD5加密
            u.password = Md5Tool.EncryptPassword(u.password);
            ef.Users.Add(u);
            ef.SaveChanges();
            return "添加用户成功";
        }

        public static bool UpdateUser(User u)
        {
            User? user = GetUserById(u.id);
            if (user != null)
            {
                EfDemoContext ef = new EfDemoContext();
                u.email = u.email??user.email;
                u.address = u.address??user.address;
                //u.image = u.image==imageNull ? 
                //u.password = u.password ?? user.password;
                u.password = Md5Tool.EncryptPassword(user.password);
                u.phone = u.phone ?? user.phone;
                u.Token = u.Token == null ? user.Token : u.Token;
                u.name = u.name ?? user.name;
                ef.Users.Update(u);
                ef.SaveChanges();
                return true;
            }
            return false;
        }

        public static bool RemoveUser(int UserNo)
        {
            EfDemoContext ef = new EfDemoContext();
            User? u = GetUserById(UserNo);
            if(u == null)
            {
                return false;
            }
            ef.Users.Remove(u);
            ef.SaveChanges();
            return true;
        }
        private static string IsValid(User u)
        {
            string pattern = @"^[A-Za-z0-9]+$";
            Regex regex = new Regex(pattern);
            //用户名判断
            if (string.IsNullOrEmpty(u.name))
            {
                return "用户名为空";
            }
            bool isValid = regex.IsMatch(u.name);
            if (!isValid)
            {
                return "用户名不合法";
            }
            //密码判断，此处已在controller层判断
            

            //邮箱判断
            if(u.email != "N/A") {
                pattern = @"[A-Za-z0-9]+@";
                List<string> mailPattern = new List<string> { "qq.com", "gmail.com", "163.com", "yaho.com", "sina.com", "aliyun.com" };
                foreach (string i in mailPattern)
                {
                    regex = new Regex(pattern + i);
                    isValid = regex.IsMatch(u.email);
                    if (isValid)
                    {
                        break;
                    }
                }
            }
            if(!isValid)
            {
                return "邮箱格式有误";
            }
            //电话判断
            if(u.phone != "N/A")
            {
                pattern = @"[0-9]{11}";
                regex = new Regex(pattern);
                isValid = regex.IsMatch(u.phone);
                if (!isValid)
                {
                    return "电话格式有误";
                }
            }
            return "";
        }

        public static bool changeIcon(int id,string path)
        {
            User? u=GetUserById(id);
            if (u==null) return false;

            EfDemoContext ef = new EfDemoContext();
            u.userIcon = path;
            ef.Users.Update(u);
            ef.SaveChanges();
            return true;
        }

        public static List<User> getAllUsers()
        {
            List<User> users = new List<User>();

            EfDemoContext efDemoContext = new EfDemoContext();
            users = efDemoContext.Set<User>().ToList();

            return users;

        }



    }
}
